#!/bin/bash

# 知识图谱关联配置 - 与故障节点ID对应
FIX_CODE_ID="DISK-FULL-001"  # 对应知识图谱中"磁盘空间耗尽（No space left）"故障ID

# 清理参数配置
THRESHOLD=85                  # 触发清理的磁盘使用率阈值(%)
MIN_FREE_SPACE_GB=10          # 最小保障可用空间(GB)
LOG_RETENTION_DAYS=7          # 日志文件保留天数
TEMP_RETENTION_DAYS=1         # 临时文件保留天数
LOG_FILE="/var/log/disk_cleaner.log"  # 清理操作日志路径

# 日志记录函数(包含知识图谱ID)
log() {
    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] [FIX_CODE_ID: $FIX_CODE_ID] $1" >> "$LOG_FILE"
}

# 获取磁盘使用状态
get_disk_usage() {
    local target_path="${1:-/}"
    df -P "$target_path" | awk 'NR==2 {
        total=$2/1024/1024
        used=$3/1024/1024
        free=$4/1024/1024
        used_percent=$5
        gsub(/%/, "", used_percent)
        print "total=" total "\nused=" used "\nfree=" free "\nused_percent=" used_percent
    }'
}

# 检查是否需要执行清理
is_cleanup_needed() {
    local usage_data=$(get_disk_usage)
    local used_percent=$(echo "$usage_data" | grep "used_percent" | cut -d'=' -f2)
    local free_space=$(echo "$usage_data" | grep "free" | cut -d'=' -f2)
    
    if (( $(echo "$used_percent >= $THRESHOLD" | bc -l) )) || 
       (( $(echo "$free_space < $MIN_FREE_SPACE_GB" | bc -l) )); then
        return 0  # 需要清理
    else
        return 1  # 无需清理
    fi
}

# 清理过期日志文件
clean_old_logs() {
    log "开始清理过期日志文件..."
    local log_directories="/var/log /var/log/nginx /var/log/mysql"
    local cleaned_count=0
    local freed_space=0
    
    for dir in $log_directories; do
        [ -d "$dir" ] || continue
        
        find "$dir" -type f -name "*.log*" ! -name "$(basename $LOG_FILE)*" -mtime +$LOG_RETENTION_DAYS | while read -r file; do
            [ -f "$file" ] || continue
            local file_size=$(du -k "$file" | cut -f1)
            rm -f "$file" && {
                ((cleaned_count++))
                freed_space=$((freed_space + file_size))
                log "已删除日志文件: $file (大小: $((file_size/1024))MB)"
            }
        done
    done
    
    freed_space=$((freed_space / 1024))
    log "日志清理完成: 共删除 $cleaned_count 个文件，释放 $freed_space MB"
    echo "count=$cleaned_count space=$freed_space"
}

# 清理过期临时文件
clean_temp_files() {
    log "开始清理过期临时文件..."
    local temp_directories="/tmp /var/tmp /var/cache"
    local cleaned_count=0
    local freed_space=0
    
    for dir in $temp_directories; do
        [ -d "$dir" ] || continue
        
        # 清理临时文件
        find "$dir" -type f -mtime +$TEMP_RETENTION_DAYS | while read -r file; do
            local file_size=$(du -k "$file" | cut -f1)
            rm -f "$file" && {
                ((cleaned_count++))
                freed_space=$((freed_space + file_size))
                log "已删除临时文件: $file (大小: $((file_size/1024))MB)"
            }
        done
        
        # 清理空目录
        find "$dir" -type d -empty -mtime +$TEMP_RETENTION_DAYS | while read -r dir_item; do
            rm -rf "$dir_item" && {
                ((cleaned_count++))
                log "已删除空目录: $dir_item"
            }
        done
    done
    
    freed_space=$((freed_space / 1024))
    log "临时文件清理完成: 共处理 $cleaned_count 项，释放 $freed_space MB"
    echo "count=$cleaned_count space=$freed_space"
}

# 清理系统缓存
clean_system_cache() {
    log "开始清理系统缓存..."
    local cleaned_count=0
    local freed_space=0
    
    # 清理包管理器缓存
    if command -v apt-get &> /dev/null; then
        local cache_before=$(du -s /var/cache/apt/archives | cut -f1)
        apt-get autoclean -y &> /dev/null && {
            ((cleaned_count++))
            local cache_after=$(du -s /var/cache/apt/archives | cut -f1)
            freed_space=$(( (cache_before - cache_after) / 1024 ))
            log "APT缓存清理完成，释放 $freed_space MB"
        }
    elif command -v yum &> /dev/null; then
        yum clean packages -y &> /dev/null && {
            ((cleaned_count++))
            log "YUM缓存清理完成"
            freed_space=500  # 估算释放空间
        }
    fi
    
    # 清理页缓存(需要root权限)
    if [ "$(id -u)" -eq 0 ]; then
        sync && echo 1 > /proc/sys/vm/drop_caches && {
            ((cleaned_count++))
            log "系统页缓存清理完成"
        }
    fi
    
    log "系统缓存清理完成: 共处理 $cleaned_count 项，释放约 $freed_space MB"
    echo "count=$cleaned_count space=$freed_space"
}

# 主执行流程
main() {
    # 初始化日志
    [ -d "$(dirname $LOG_FILE)" ] || mkdir -p "$(dirname $LOG_FILE)"
    log "===== 磁盘清理程序启动 (FIX_CODE_ID: $FIX_CODE_ID) ====="
    
    # 记录初始状态
    local initial_usage=$(get_disk_usage)
    local initial_percent=$(echo "$initial_usage" | grep "used_percent" | cut -d'=' -f2)
    log "初始磁盘使用率: $initial_percent%"
    
    # 检查是否需要清理
    if ! is_cleanup_needed; then
        log "磁盘空间充足，无需清理"
        log "===== 程序正常结束 ====="
        exit 0
    fi
    
    log "检测到磁盘空间不足，启动清理流程"
    local total_freed=0
    
    # 第一阶段: 清理日志
    log_result=$(clean_old_logs)
    total_freed=$((total_freed + $(echo "$log_result" | grep "space=" | cut -d'=' -f2)))
    
    # 第二阶段: 清理临时文件(如仍需)
    if is_cleanup_needed; then
        temp_result=$(clean_temp_files)
        total_freed=$((total_freed + $(echo "$temp_result" | grep "space=" | cut -d'=' -f2)))
        
        # 第三阶段: 清理系统缓存(如仍需)
        if is_cleanup_needed; then
            cache_result=$(clean_system_cache)
            total_freed=$((total_freed + $(echo "$cache_result" | grep "space=" | cut -d'=' -f2)))
        fi
    fi
    
    # 记录最终状态
    local final_usage=$(get_disk_usage)
    local final_percent=$(echo "$final_usage" | grep "used_percent" | cut -d'=' -f2)
    log "清理完成，总计释放 $total_freed MB 空间"
    log "清理后磁盘使用率: $final_percent%"
    
    if is_cleanup_needed; then
        log "警告: 磁盘空间仍不足，建议人工干预"
        log "===== 程序异常结束 ====="
        exit 1
    else
        log "磁盘空间已恢复正常水平"
        log "===== 程序正常结束 ====="
        exit 0
    fi
}

# 启动主程序
main
